package com.lp.controller;

import com.lp.po.User;
import com.lp.service.StudentService;
import com.lp.service.UserService;
import com.lp.userException.CustomException;
import com.lp.utils.MDUtils;
import com.lp.utils.RegistUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/Password")
public class SSSSSSSSPasswordController {
    @Resource
    private UserService userService;
    @Resource
    private StudentService studentService;
    RegistUtil registUtil=new RegistUtil();

    /***************************账户密码设置****************************************/
    //运行Ajax进行提交   输入用户名后自动填写完输入框
    @RequestMapping("/selectStudentByName")
    @ResponseBody
    public Map<String,Object> selectStudentByName(String username) throws Exception {
        User users=userService.findUserByName(username);
        Map<String,Object> mapUser=new HashMap<String,Object>();
        if(users!=null){
            mapUser.put("type", "success");
            mapUser.put("role", users.getRole());
            return mapUser;
        }else {
            mapUser.put("type", "error");
            return mapUser;
        }
    }

    // 普通用户账号密码重置
    @RequestMapping("/userPasswordRest")
    public String userPasswordRestUI() throws Exception {
        return "/admin/ssssssss";
    }
    // 普通用户账号密码重置处理
    @RequestMapping(value = "/doUserPasswordRest", method = {RequestMethod.POST})
    public String userPasswordRest(String password,Integer role,String username,Model model) throws Exception {
        User u = userService.findUserIdWithUserName(username);
        if (u != null) {
            if((username.indexOf(" ")!=-1)){
                throw new CustomException("格式有错误，请认真填写");
            }
            if(password.equals("")){
                password="123456";
            }
            u.setPassword(MDUtils.getMD5Password(password,registUtil.getSalt(username)).toString());
            userService.updateById(username,u.getPassword(),role,u.getUserid());
            studentService.updateWithPassword(username,password);
            model.addAttribute("msg","重置成功");
        } else {
            model.addAttribute("msg","没有该用户");
        }
        return "/admin/ssssssss";
    }
}